<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="cn.edu.ecut.se2024.model.supplier_mgmt.Supplier" %>
<%@ page import="cn.edu.ecut.se2024.model.supplier_mgmt.SupplierContact" %>
<%@ page import="cn.edu.ecut.se2024.model.supplier_mgmt.SupplierAddress" %>
<%@ page import="cn.edu.ecut.se2024.controller.SupplierMgmtController" %>

<style type="text/css">
	.center-div {
		display: grid;
		place-items: center;  /* 同时在水平和垂直方向上居中 */
	}
	input[type="text"] {
		border: 2px solid #CCCCCC;
		border-radius: 8px;  /* 圆角 */
		height: 25px;
	}
	.button {
		border: none;
		border-radius: 5px;  /* 按钮圆角 */
		transition-duration: 0.3s;  /* 过渡效果持续时间 */
		font-size: 16px;
		color: #FFFFFF;
		background-color: #4B9E5F;
		width: 80px;
		height: 40px;
	}
	.button:hover {
		background-color: #4682B4;
	}
	.delete-button {
		background-color: #FF0000;
	}
	.delete-button:hover {
		background-color: #DC143C;
	}
	.delete-button:disabled {
		background-color: #DDDDDD;
	}
	.delete-button:disabled:hover {
		background-color: #DDDDDD;
	}
	.button-table {
		border-collapse: collapse;
		border-spacing: 5px;
	}
	.button-table td {
		text-align: center;
		vertical-align: center;
		padding: 15px;
	}
	.table-div {
		width: 950px;
		max-height: 200px;
		overflow-x: auto;
		overflow-y: auto;
	}
	.table {
		border-collapse: collapse;
		border-spacing: 0px;
	}
	.table input[type="checkbox"] {
		transform: scale(1.5);
	}
	.table tbody tr:hover{
		background-color: #DCDCDC;
	}
	.table th, .table td {
		white-space: nowrap;
		text-align: center;
		vertical-align: center;
		padding: 8px;
		border: 2px solid #DDDDDD;
	}
	.table th {
		background-color: #F9F9F9;
		position: sticky;  /* 固定表头 */
		top: 0;
		z-index: 1;
	}
</style>

<%	// 获取用户权力
	String user_power = (String)request.getSession().getAttribute(SupplierMgmtController.SUPPLIER_MGMT_POWER);
	// 判断用户是否有管理权力
	boolean have_mgmt_power = false;
	if (user_power != null && user_power.equals(SupplierMgmtController.SUPPLIER_MGMT_POWER_MGMT)) {
		have_mgmt_power = true;
	}
	// 判断是否有供应商信息
	boolean have_supplier = false;
	// 获取供应商信息
	Supplier supplier = (Supplier)request.getAttribute(SupplierMgmtController.SUPPLIER_MGMT_SUPPLIER);
	// 如果没有供应商信息则构造一个空的默认供应商信息
	if (supplier == null) {
		supplier = new Supplier(true);
	}
	else {
		have_supplier = true;
	}
	// 获取操作动作
	String action = (String)request.getAttribute(SupplierMgmtController.SUPPLIER_MGMT_ACTION);
	boolean action_add = action.equals(SupplierMgmtController.SUPPLIER_MGMT_ACTION_ADD);
	boolean action_update = action.equals(SupplierMgmtController.SUPPLIER_MGMT_ACTION_UPDATE);
	boolean action_see = !(action_add || action_update);
%>

<div class="center-div">
	<!-- 表头 -->
	<h3><%=action_add ? "增加" : (action_update ? "修改" : "查看") %>供应商信息</h3>
	
	<!-- 供应商基本属性 -->
	<p>
		&nbsp;&nbsp;
		<label>供应商ID：</label>
			<input id="id" type="text" name="id" value="<%=have_supplier ? supplier.getId() : "" %>" placeholder="ID自动生成，无需填写！" readonly>
		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		<label>供应商名称：</label>
			<input id="name" type="text" name="name" value="<%=have_supplier ? supplier.getName() : "" %>" <%=action_see ? "readonly" : "" %> placeholder="不超过50个字！">
	</p>
	<p>
		<label>供应商类型：</label>
			<input id="type" type="text" name="type" value="<%=have_supplier ? supplier.getType() : "" %>" <%=action_see ? "readonly" : "" %> placeholder="不超过20个汉字！">
		&nbsp;&nbsp;&nbsp;&nbsp;
		<label>供应商银行账户：</label>
			<input id="bank" type="text" name="bank" value="<%=have_supplier ? supplier.getBank() : "" %>" <%=action_see ? "readonly" : "" %> placeholder="16-19位数字！">
	</p>
	
	<!-- 供应商地址列表 -->
	<p>
		<label>地址信息：</label>
	<%
		if (!action_see) {
		%>
			<input type="button" class="button" name="addOneAddressRow" value="增加一行" onclick="addAddressRow()">
	<%	}
		%>
	</p>
	<div class="center-div table-div">
		<table id="AddressTable" class="table">
			<thead><tr>
				<th>默认</th><th>地址</th>
	<%
			if (!action_see) {
		%>
				<th>删除</th>
	<%		}
		%>
			</tr></thead>
			<tbody>
	<%
			for(SupplierAddress sa: supplier.getAddress()) {
		%>
				<tr>
					<td><input type="checkbox" onclick="checkOnlyOne('AddressTable',this)" <%=sa.isDefaults() ? "checked" : "" %> <%=action_see ? "disabled" : "" %>></td>
					<td><input type="text" name="address" value="<%=sa.getAddress() %>" <%=action_see ? "readonly" : "" %> placeholder="由-或汉字或数字组成且不超过50个字！" style="width: 230px;"></td>
	<%
				if (!action_see) {
		%>
					<td><input type="button" class="button delete-button" name="deleteAddressRow" value="删除" onclick="deleteRow('AddressTable',this)" <%=supplier.getAddress().size() == 1 ? "disabled" : "" %>></td>
	<%			}
		%>
				</tr>
	<%		}
		%>
			</tbody>
		</table>
	</div>
	<br>
	
	<!-- 供应商联系人列表 -->
	<p>
		<label>联系人信息：</label>
	<%
		if (!action_see) {
		%>
			<input type="button" class="button" name="addOneContactRow" value="增加一行" onclick="addContactRow()">
	<%	}
		%>
	</p>
	<div class="center-div table-div">
		<table id="ContactTable" class="table">
			<thead><tr>
				<th>默认</th><th>姓名</th><th>电话</th><th>职位</th>
	<%
			if (!action_see) {
		%>
				<th>删除</th>
	<%		}
		%>
			</tr></thead>
			<tbody>
	<%
			for(SupplierContact sc: supplier.getContact()) {
		%>
				<tr>
					<td><input type="checkbox" onclick="checkOnlyOne('ContactTable',this)" <%=sc.isDefaults() ? "checked" : "" %> <%=action_see ? "disabled" : "" %>></td>
					<td><input type="text" name="contactname" value="<%=sc.getName() %>" <%=action_see ? "readonly" : "" %> placeholder="由汉字或英文字母组成且为2-20个字！" style="width: 230px;"></td>
					<td><input type="text" name="contactphone" value="<%=sc.getPhone() %>" <%=action_see ? "readonly" : "" %> placeholder="7-12位数字！"></td>
					<td><input type="text" name="contactposition" value="<%=sc.getPosition() %>" <%=action_see ? "readonly" : "" %> placeholder="2-30个汉字！"></td>
	<%
				if (!action_see) {
		%>
					<td><input type="button" class="button delete-button" name="deleteContactRow" value="删除" onclick="deleteRow('ContactTable',this)" <%=supplier.getContact().size() == 1 ? "disabled" : "" %>></td>
	<%			}
		%>
				</tr>
	<%		}   
		%> 
			</tbody>
		</table>
	</div>
	<br>
	
	<!-- 操作按钮表格 -->
	<table class="button-table">
		<tr>
			<td><input type="button" class="button" value="<%=action_see ? "关闭" : "取消" %>" onclick="cancelSupplier(<%=action_see ? "'close'" : "'cancel'" %>)"></td>
	<%
		if (!action_see) {
		%>
			<td><input type="button" class="button" value="<%=action_add ? "增加" : (action_update ? "修改" : "") %>" onclick="actionSupplier()"></td>
	<%	}
		%>
		</tr>
	</table>
</div>

<!-- 隐藏的“取消（关闭）”提交表单 -->
<form id="cancelSupplierForm" action="<%=have_mgmt_power ? "suppliermgmt.mgmt" : "suppliermgmt.see" %>" method="post" style="display: none;"></form>
<!-- 隐藏的“增加、修改”提交表单 -->
<form id="actionSupplierForm" action="<%=action_add ? "suppliermgmt.addSupplier" : (action_update ? "suppliermgmt.updateSupplier" : "") %>" method="post" style="display: none;">
	<input id="supplier_json" type="hidden" name="supplier_json" value="">
</form>

<script>
	// 地址列表索引
	const ADDRESS_DEFAULTS = 0;
	const ADDRESS_ADDRESS = 1;
	const ADDRESS_DELETE = 2;
	const CONTACT_DEFAULTS = 0;
	// 联系人列表索引
	const CONTACT_NAME = 1;
	const CONTACT_PHONE = 2;
	const CONTACT_POSITION = 3;
	const CONTACT_DELETE = 4;
	// 列表ID
	const ADDRESS_TABLE = "AddressTable";
	const CONTACT_TABLE = "ContactTable";
	
	var lastAddressCheckbox = null;  // 上一个选中的地址表复选框
	var lastContactCheckbox = null;  // 上一个选中的联系人表复选框

	// 保证必须选中表格的一行
	function checkOnlyOne(tableId,checkbox) {
		// 取消选中上一个选中的复选框
		if (tableId === ADDRESS_TABLE && lastAddressCheckbox !== null && checkbox !== lastAddressCheckbox) {
			lastAddressCheckbox.checked = false;
			lastAddressCheckbox = checkbox;
		}
		else if (tableId === CONTACT_TABLE && lastContactCheckbox !== null && checkbox !== lastContactCheckbox) {
			lastContactCheckbox.checked = false;
			lastContactCheckbox = checkbox;
		}
		// 不允许取消勾选复选框
		checkbox.checked = true;
	}
	// 为地址列表增加一行
	function addAddressRow() {
		var table = document.getElementById(ADDRESS_TABLE).getElementsByTagName('tbody')[0];
		var newRow = table.insertRow();
		var defaults = newRow.insertCell(ADDRESS_DEFAULTS);
		var address = newRow.insertCell(ADDRESS_ADDRESS);
		var delete_button = newRow.insertCell(ADDRESS_DELETE);
		defaults.innerHTML = '<input type="checkbox" onclick="checkOnlyOne(\'AddressTable\',this)">';
		address.innerHTML = '<input type="text" name="address" value="" placeholder="由-或汉字或数字组成且不超过50个字！" style="width: 230px;">';
		delete_button.innerHTML = '<input type="button" class="button delete-button" name="deleteAddressRow" value="删除" onclick="deleteRow(\'AddressTable\',this)">';
		checkDeleteButton(ADDRESS_TABLE);  // 检查删除按钮
	}
	// 为联系人列表增加一行
	function addContactRow() {
		var table = document.getElementById(CONTACT_TABLE).getElementsByTagName('tbody')[0];
		var newRow = table.insertRow();
		var defaults = newRow.insertCell(CONTACT_DEFAULTS);
		var name = newRow.insertCell(CONTACT_NAME);
		var phone = newRow.insertCell(CONTACT_PHONE);
		var position = newRow.insertCell(CONTACT_POSITION);
		var delete_button = newRow.insertCell(CONTACT_DELETE);
		defaults.innerHTML = '<input type="checkbox" onclick="checkOnlyOne(\'ContactTable\',this)">';
		name.innerHTML = '<input type="text" name="contactname" value="" placeholder="由汉字或英文字母组成且为2-20个字！" style="width: 230px;">';
		phone.innerHTML = '<input type="text" name="contactphone" value="" placeholder="7-12位数字！">';
		position.innerHTML = '<input type="text" name="contactposition" value="" placeholder="2-30个汉字！">';
		delete_button.innerHTML = '<input type="button" class="button delete-button" name="deleteContactRow" value="删除" onclick="deleteRow(\'ContactTable\',this)">';
		checkDeleteButton(CONTACT_TABLE);  // 检查删除按钮
	}
	// 当列表只剩一行时不允许删除该行
	function checkDeleteButton(tableId) {
		var table = document.getElementById(tableId);
		var rows = table.rows.length;
		var deleteButtons = table.getElementsByClassName("delete-button");
		if (rows === 2) {  // 包含表头
			deleteButtons[0].disabled = true;
		}
		else {
			deleteButtons[0].disabled = false;
		}
	}
	// 删除列表的某一行
	function deleteRow(tableId,button) {
		var row = button.parentNode.parentNode;
		var table = document.getElementById(tableId);
		// 该行是否勾选了前面的复选框
		var isChecked = row.querySelector('input[type="checkbox"]').checked;
		
		row.parentNode.removeChild(row);
		checkDeleteButton(tableId);  // 检查删除按钮
		
		// 如果勾选了则勾选第一行的复选框作为默认
		if (isChecked) {
			var checkboxes = document.querySelectorAll('#' + tableId + ' input[type="checkbox"]');
			checkboxes[0].checked = true;
			// 重新设置上一个勾选的复选框
			if (tableId === ADDRESS_TABLE) {
				lastAddressCheckbox = checkboxes[0];
			}
			else if (tableId === CONTACT_TABLE) {
				lastContactCheckbox = checkboxes[0];
			}
		}
	}
	// 搜索列表的所有复选框以设置上一个勾选的复选框
	function searchCheckboxChecked(tableId) {
		var checkboxes = document.querySelectorAll('#' + tableId + ' input[type="checkbox"]');
		checkboxes.forEach(function(checkbox) {
			if (checkbox.checked) {
				if (tableId === ADDRESS_TABLE) {
					lastAddressCheckbox = checkbox;
					return;
				}
				else if (tableId === CONTACT_TABLE) {
					lastContactCheckbox = checkbox;
					return;
				}
			}
		});
	}
	// 为指定表格添加监听器以实现点击表格行勾选该行复选框
	function addEventListenerForTable(tableId) {
		var table = document.getElementById(tableId);
		table.addEventListener("click", function(event) {
			var target = event.target;
			if (target.tagName.toLowerCase() === "td") {
				var row = target.parentNode;
				// 查找该行内的复选框
				var checkbox = row.querySelector("input[type='checkbox']");
				if (checkbox && !checkbox.disabled) {
					checkbox.click();
				}
			}
		});
	}
	
	searchCheckboxChecked(ADDRESS_TABLE);
	searchCheckboxChecked(CONTACT_TABLE);
	addEventListenerForTable(ADDRESS_TABLE);
	addEventListenerForTable(CONTACT_TABLE);
	
	// 发起取消请求
	function cancelSupplier(action) {
		var ok = true;
		if (action === "cancel") {
			ok = confirm("确定取消本次操作吗？");
		}
		if (ok) {
			document.getElementById("cancelSupplierForm").submit();
		}
	}
	// 移除所有数据的前后空白字符
	function removeSpace() {
		document.getElementById("id").value = document.getElementById("id").value.trim();
		document.getElementById("name").value = document.getElementById("name").value.trim();
		document.getElementById("type").value = document.getElementById("type").value.trim();
		document.getElementById("bank").value = document.getElementById("bank").value.trim();
		
		var have_address_defaults = false;
		var tableAddress = document.getElementById(ADDRESS_TABLE);
		var rows = tableAddress.getElementsByTagName("tr");
		for (var i = 1; i < rows.length; i++) {
			var cells = rows[i].getElementsByTagName("td");
			if (!have_address_defaults) {
				have_address_defaults = cells[ADDRESS_DEFAULTS].getElementsByTagName("input")[0].checked;
			}
			cells[ADDRESS_ADDRESS].getElementsByTagName("input")[0].value = cells[ADDRESS_ADDRESS].getElementsByTagName("input")[0].value.trim();
		}
		if (!have_address_defaults) {
			alert("请选择一个地址作为默认地址！");
			return false;
		}
		
		var have_contact_defaults = false;
		var tableContact = document.getElementById(CONTACT_TABLE);
		var rows = tableContact.getElementsByTagName("tr");
		for (var i = 1; i < rows.length; i++) {
			var cells = rows[i].getElementsByTagName("td");
			if (!have_contact_defaults) {
				have_contact_defaults = cells[CONTACT_DEFAULTS].getElementsByTagName("input")[0].checked;
			}
			cells[CONTACT_NAME].getElementsByTagName("input")[0].value = cells[CONTACT_NAME].getElementsByTagName("input")[0].value.trim();
			cells[CONTACT_PHONE].getElementsByTagName("input")[0].value = cells[CONTACT_PHONE].getElementsByTagName("input")[0].value.trim();
			cells[CONTACT_POSITION].getElementsByTagName("input")[0].value = cells[CONTACT_POSITION].getElementsByTagName("input")[0].value.trim();
		}
		if (!have_contact_defaults) {
			alert("请选择一个联系人作为默认联系人！");
			return false;
		}
		
		return true;
	}
	// 检查填写供应商信息是否正确
	function checkSupplierInformation() {
		var remove_ok = removeSpace();  // 移除所有数据的前后空白字符
		
		if (remove_ok) {
			// 正则表达式
			var regex_name = /^.{1,50}$/;
			var regex_type = /^[\u4e00-\u9fa5]{1,20}$/;
			var regex_bank = /^\d{16,19}$/;
			var regex_address = /^[\u4e00-\u9fa5\d-]{1,50}$/;
			var regex_contact_name = /^[\u4e00-\u9fa5a-zA-Z]{2,20}$/;
			var regex_contact_position = /^[\u4e00-\u9fa5]{2,30}$/;
			var regex_contact_phone = /^\d{7,12}$/;
			
			var name = document.getElementById("name").value;
			var type = document.getElementById("type").value;
			var bank = document.getElementById("bank").value;
			if (name === "" || !regex_name.test(name)) {
				if (name === "") {
					alert("请填写供应商名称！");
				}
				else {
					alert("供应商名称应该不超过50个字！");
				}
				return false;
			}
			else if (type === "" || !regex_type.test(type)) {
				if (type === "") {
					alert("请填写供应商类型！");
				}
				else {
					alert("供应商类型应该为不超过20个字的汉字！");
				}
				return false;
			}
			else if (bank === "" || !regex_bank.test(bank)) {
				if (bank === "") {
					alert("请填写供应商银行账户！");
				}
				else {
					alert("供应商银行账户应该为16-19位数字！");
				}
				return false;
			}
			
			var tableAddress = document.getElementById(ADDRESS_TABLE);
			var rows = tableAddress.getElementsByTagName("tr");
			for (var i = 1; i < rows.length; i++) {
				var cells = rows[i].getElementsByTagName("td");
				var address = cells[ADDRESS_ADDRESS].getElementsByTagName("input")[0].value;

				if (cells[ADDRESS_DEFAULTS].getElementsByTagName("input")[0].checked) {
					if (address === "" || !regex_address.test(address)) {
						if (address === "") {
							alert("必须填写默认地址！");
						}
						else {
							alert("供应商地址应该由-或汉字或数字组成且不超过50个字！");
						}
						return false;
					}
				}
				else {
					if (address !== "" && !regex_address.test(address)) {
						alert("供应商地址应该由-或汉字或数字组成且不超过50个字！");
						return false;
					}
					else if (address === "") {  // 忽略非默认空行地址
						continue;
					}
				}
			}
			
			var tableContact = document.getElementById(CONTACT_TABLE);
			var rows = tableContact.getElementsByTagName("tr");
			for (var i = 1; i < rows.length; i++) {
				var cells = rows[i].getElementsByTagName("td");
				var contact_name = cells[CONTACT_NAME].getElementsByTagName("input")[0].value;
				var contact_phone = cells[CONTACT_PHONE].getElementsByTagName("input")[0].value;
				var contact_position = cells[CONTACT_POSITION].getElementsByTagName("input")[0].value;

				if (cells[CONTACT_DEFAULTS].getElementsByTagName("input")[0].checked) {
					if (contact_name === "" || contact_position === "" || contact_phone === "") {
						alert("必须填写默认联系人的所有信息！");
						return false;
					}
				}
				else {
					if (!(contact_name === "" && contact_position === "" && contact_phone === "")
							&& !(contact_name !== "" && contact_position !== "" && contact_phone !== "")) {
						alert("不允许仅填写一行联系人的部分信息！");
						return false;
					}
					// 忽略非默认空行联系人
					else if (contact_name === "" && contact_position === "" && contact_phone === "") {
						continue;
					}
				}
	        
				if (!regex_contact_name.test(contact_name)) {
					alert("所有供应商联系人姓名应该由汉字或英文字母组成且为2-20个字！");
					return false;
				}
				else if (!regex_contact_phone.test(contact_phone)) {
					alert("所有供应商联系人电话应该为7-12位数字！");
					return false;
				}
				else if (!regex_contact_position.test(contact_position)) {
					alert("所有供应商联系人职位应该为2-30个汉字！");
					return false;
				}
			}
			
			return true;
		}
		else {
			return remove_ok;
		}
	}
	// 发起动作请求
	function actionSupplier() {
		// 检查填写供应商信息是否正确
		if(checkSupplierInformation()) {
			var id = document.getElementById("id").value;
			var name = document.getElementById("name").value;
			var type = document.getElementById("type").value;
			var bank = document.getElementById("bank").value;

			// 封装地址列表数据
			var tableAddressData = [];
			var tableAddress = document.getElementById(ADDRESS_TABLE);
			var rows = tableAddress.getElementsByTagName("tr");
			for (var i = 1; i < rows.length; i++) {
				var cells = rows[i].getElementsByTagName("td");
				// 忽略空地址行
				if (cells[ADDRESS_ADDRESS].getElementsByTagName("input")[0].value === "") {
					continue;
				}
				
				var rowData = {
					sid: (document.getElementById("id").value === "" ? -1 : document.getElementById("id").value),
					id: -1,
					address: cells[ADDRESS_ADDRESS].getElementsByTagName("input")[0].value,
					defaults: (cells[ADDRESS_DEFAULTS].getElementsByTagName("input")[0].checked ? 1 : 0)
				};
				tableAddressData.push(rowData);
			}

			// 封装联系人列表数据
			var tableContactData = [];
			var tableContact = document.getElementById("ContactTable");
			var rows = tableContact.getElementsByTagName("tr");
			for (var i = 1; i < rows.length; i++) {
				var cells = rows[i].getElementsByTagName("td");
				// 忽略空联系人行
				if (cells[CONTACT_NAME].getElementsByTagName("input")[0].value === "") {
					continue;
				}
				
				var rowData = {
					sid: (document.getElementById("id").value === "" ? -1 : document.getElementById("id").value),
					id: -1,
					name: cells[CONTACT_NAME].getElementsByTagName("input")[0].value,
					phone: cells[CONTACT_PHONE].getElementsByTagName("input")[0].value,
					position: cells[CONTACT_POSITION].getElementsByTagName("input")[0].value,
					defaults: (cells[CONTACT_DEFAULTS].getElementsByTagName("input")[0].checked ? 1 : 0)
				};
				tableContactData.push(rowData);
			}
			
			// 将所有数据封装成供应商对象
			var supplier = {
				id: id,
				name: name,
				type: type,
				bank: bank,
				address: tableAddressData,
				contact: tableContactData
			};
			// 将封装好的数据转换为JSON格式字符串并设置在隐藏的“增加、修改”提交表单中
			document.getElementById("supplier_json").value = JSON.stringify(supplier);
			document.getElementById("actionSupplierForm").submit();
		}
	}
</script>
